__author__ = 'shawhen'

from PyQt5.QtWidgets import *

from collections import OrderedDict

from ...uranome import load_later as m_load_later

from . import catalog_tab_widget as m_catalog_tab_widget


class CatalogGallery(QWidget):
    def __init__(self, parent=None):
        super(CatalogGallery, self).__init__(parent)

        from . import ui_catalog_gallery as m_ui

        self.ui = m_ui.Ui_CatalogGallery()
        self.ui.setupUi(self)

        self.ui.lineEdit.hide()

        self._wait_widget = m_load_later.LoadLater()
        self.ui.widget_5.layout().addWidget(self._wait_widget)

        self.ui.all_push_button.clicked.connect(lambda : self._show_catalog_content("__**all**__"))

        self._catalog_tab_button_group = None

        self._catalog_tabs = OrderedDict()
        self._catalog_detail_row_num = 0
        self._catalog_detail_widgets = OrderedDict()  # id: []

        self._cur_catalog = None  # 当前正在显示哪一分类的详细
        self._cur_show_catalog_detail_num = 0  # 当前显示的分类详细有多少个？

    def set_wait(self):
        self._wait_widget.show()

    def end_wait(self):
        self._wait_widget.hide()

    def init(self, catalogs, catalog_detail_row_num):
        self._catalogs = catalogs
        self._catalog_detail_row_num = catalog_detail_row_num

        while True:
            item = self.ui.stack_catalog_tabs_widget.layout().takeAt(0)
            if item is None:
                break
            widget = item.widget()
            widget.deleteLater()
        for i in range(0, self.ui.catalog_detail_widgets_layout.count()):
            item = self.ui.catalog_detail_widgets_layout.itemAt(i)
            if item is None:
                break
            widget = item.widget()
            self.ui.catalog_detail_widgets_layout.removeWidget(widget)
            widget.setParent(None)

        self._catalog_tabs.clear()
        self._catalog_detail_widgets.clear()

        self._catalog_tab_button_group = QButtonGroup()
        self._catalog_tab_button_group.setExclusive(True)

        self._catalog_tab_button_group.addButton(self.ui.all_push_button)
        self._cur_catalog = "__**all**__"
        self._cur_show_catalog_detail_num = 0

        def _make_catalog_tab(parent_catalog_id, catalog_id, catalog_context):
            catalog_tab_widget = m_catalog_tab_widget.CatalogTabWidget()
            if parent_catalog_id is None:
                catalog_full_id = catalog_id
                self._catalog_tabs[catalog_full_id] = {"widget": catalog_tab_widget}
            else:
                catalog_full_id = parent_catalog_id+":"+catalog_id

                if "children" not in self._catalog_tabs[parent_catalog_id]:
                    self._catalog_tabs[parent_catalog_id]["children"] = OrderedDict()
                self._catalog_tabs[parent_catalog_id]["children"][catalog_full_id] = {"widget": catalog_tab_widget}

            catalog_tab_widget.set_name(catalog_context["display"])
            self._catalog_tab_button_group.addButton(catalog_tab_widget.ui.show_button)

            catalog_tab_widget.ui.show_button.clicked.connect(lambda : self._show_catalog_content(catalog_full_id))

            if parent_catalog_id is None:
                catalog_tab_widget.hide_navi("parent")
            else:
                catalog_tab_widget.ui.parent_button.clicked.connect(lambda : self._switch_catalog_tabs(catalog_full_id, "parent"))

            catalog_children = catalog_context.get("children")
            if catalog_children is None:
                catalog_tab_widget.hide_navi("children")
            else:
                catalog_tab_widget.ui.children_button.clicked.connect(lambda : self._switch_catalog_tabs(catalog_full_id, "children"))

                if isinstance(catalog_children, list):
                    for child_catalog_id, child_catalog_context in catalog_children:
                        _make_catalog_tab(catalog_full_id, child_catalog_id, child_catalog_context)
                elif isinstance(catalog_children, dict):
                    for child_catalog_id, child_catalog_context in catalog_children.items():
                        _make_catalog_tab(catalog_full_id, child_catalog_id, child_catalog_context)

        if isinstance(catalogs, list):
            for catalog_id, catalog_context in catalogs:
                _make_catalog_tab(None, catalog_id, catalog_context)
        elif isinstance(catalogs, dict):
            for catalog_id, catalog_context in catalogs.items():
                _make_catalog_tab(None, catalog_id, catalog_context)

        # 展示顶层分类
        for catalog_tab_full_id, catalog_tab_context in self._catalog_tabs.items():
            self.ui.stack_catalog_tabs_widget.layout().addWidget(catalog_tab_context["widget"])

    def _switch_catalog_tabs(self, catalog_full_id, direction):
        print("switch catalog:", catalog_full_id, "direction:", direction)

        catalog_ids = catalog_full_id.split(":")
        target_catalog_tab = None
        if direction == "children":
            root_catalog = self._catalog_tabs[catalog_ids[0]]
            target_catalog_tab = root_catalog.get("children")
            target_catalog_full_id = catalog_ids[0]
            for catalog_id_i in catalog_ids[1:]:
                target_catalog_full_id += ":"+catalog_id_i
                target_catalog_tab = target_catalog_tab[target_catalog_full_id].get("children")
        elif direction == "parent":
            root_catalog = self._catalog_tabs
            target_catalog_tab = root_catalog
            target_catalog_full_id = catalog_ids[0]
            for catalog_id_i in catalog_ids[1:-1]:
                target_catalog_full_id += ":"+catalog_id_i
                target_catalog_tab = root_catalog[target_catalog_full_id].get("children")
        else:
            raise NotImplementedError

        while True:
            item = self.ui.stack_catalog_tabs_widget.layout().takeAt(0)
            if item is None:
                break
            item.widget().hide()

        if target_catalog_tab is not None:
            for child_catalog_full_id, child_catalog_context in target_catalog_tab.items():
                child_catalog_widget = child_catalog_context.get("widget")
                self.ui.stack_catalog_tabs_widget.layout().addWidget(child_catalog_widget)
                child_catalog_widget.show()
        else:
            raise ValueError("target catalog tab is None")

        self.ui.stack_catalog_tabs_widget.hide()
        self.ui.stack_catalog_tabs_widget.show()

    def _show_catalog_content(self, catalog_full_id):
        print("show catalog:", catalog_full_id)
        self._cur_catalog = catalog_full_id
        self._cur_show_catalog_detail_num = 0

        if catalog_full_id == "__**all**__":
            for catalog_full_id_i, catalog_detail_widgets in self._catalog_detail_widgets.items():
                for widget in catalog_detail_widgets:
                    # 重新排列
                    column_to_put = self._cur_show_catalog_detail_num // self._catalog_detail_row_num
                    row_to_put = self._cur_show_catalog_detail_num % self._catalog_detail_row_num

                    self.ui.catalog_detail_widgets_layout.addWidget(widget, row_to_put, column_to_put)

                    widget.show()
                    self._cur_show_catalog_detail_num += 1
        else:
            # 先全部隐藏再说
            for catalog_full_id_i, catalog_detail_widgets in self._catalog_detail_widgets.items():
                for widget in catalog_detail_widgets:
                    widget.hide()
            # 将需要显示的重新排列在布局上
            for catalog_full_id_i, catalog_detail_widgets in self._catalog_detail_widgets.items():
                if catalog_full_id_i.startswith(catalog_full_id):  # 子分类
                    for widget in catalog_detail_widgets:
                        # 重新排列
                        column_to_put = self._cur_show_catalog_detail_num // self._catalog_detail_row_num
                        row_to_put = self._cur_show_catalog_detail_num % self._catalog_detail_row_num

                        self.ui.catalog_detail_widgets_layout.addWidget(widget, row_to_put, column_to_put)

                        self._cur_show_catalog_detail_num += 1
                        widget.show()
                else:
                    for widget in catalog_detail_widgets:
                        widget.hide()

    def add_catalog_detail(self, catalog_full_id, catalog_detail_widget):
        catalog_detail_widgets_num = 0
        for catalog_detail_widget_id, catalog_detail_widgets in self._catalog_detail_widgets.items():
            catalog_detail_widgets_num += len(catalog_detail_widgets)

        if catalog_full_id not in self._catalog_detail_widgets:
            self._catalog_detail_widgets[catalog_full_id] = []
        self._catalog_detail_widgets[catalog_full_id].append(catalog_detail_widget)

        if self._cur_catalog == "__**all**__" or catalog_full_id.startswith(self._cur_catalog):
            # 显示
            column_to_put = self._cur_show_catalog_detail_num // self._catalog_detail_row_num
            row_to_put = self._cur_show_catalog_detail_num % self._catalog_detail_row_num

            self.ui.catalog_detail_widgets_layout.addWidget(catalog_detail_widget, row_to_put, column_to_put)
            self._cur_show_catalog_detail_num += 1
        else:  # 暂不显示
            pass